package com.huilian.iotbox.admin.wap.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.huilian.iotbox.admin.wap.dao.LedgerCommodityDao;
import com.huilian.iotbox.admin.wap.dao.LedgerMerchantDao;
import com.huilian.iotbox.admin.wap.dao.LedgerMerchantRecordDao;
import com.huilian.iotbox.admin.wap.service.LedgerMerchantRecordService;
import com.huilian.iotbox.data.common.ServerResponse;
import com.huilian.iotbox.data.dto.LedgerMerchantDto;
import com.huilian.iotbox.data.dto.LedgerMerchantRecordDto;
import com.huilian.iotbox.data.enums.LedgerMerchantFailureStatusEnum;
import com.huilian.iotbox.data.enums.LedgerMerchantFailureStatusEunm;
import com.huilian.iotbox.data.enums.RoleEnum;
import com.huilian.iotbox.data.po.LedgerMerchant;
import com.huilian.iotbox.data.po.LedgerMerchantRecord;
import com.huilian.iotbox.data.utils.DateTimeUtils;
import com.huilian.iotbox.data.vo.LedgerMerchantRecordVo;
import com.huilian.iotbox.data.vo.LedgerMerchantVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class LedgerMerchantRecordServiceImpl implements LedgerMerchantRecordService {
    @Resource
    private LedgerMerchantRecordDao ledgerMerchantRecordDao;

    @Resource
    private LedgerMerchantDao ledgerMerchantDao;

    @Resource
    private LedgerCommodityDao ledgerCommodityDao;

    @Transactional
    @Override
    public ServerResponse editLedgerMerchantOrRecord(LedgerMerchantRecordDto ledgerMerchantRecordDto) {
        //不等于1，2，3，无权限操作
        Integer[] roleIdArray = {
                RoleEnum.AGENT.getRoleId(),
                RoleEnum.SUPER_ADMINISTRATOR.getRoleId(),
                RoleEnum.MERCHANT.getRoleId()
        };
        boolean contains = Arrays.asList(roleIdArray).contains(ledgerMerchantRecordDto.getUserInfo().getRoleId());
        if(!contains){
            return ServerResponse.createByErrorMessage("暂无操作权限！");
        }

        //判断场地是否已经存在记录表 根据条件 failureTime失效时间为null和场地id查询
        LedgerMerchant ledgerMerchant =ledgerMerchantDao.findOneLedgerMerchant(ledgerMerchantRecordDto);
        if(ObjectUtils.isEmpty(ledgerMerchant)){
            //添加场地记录
            LedgerMerchant ledgerMerchant1 = this.addLedgerMerchant(ledgerMerchantRecordDto);
            //添加分账信息
            this.ledgerMerchantRecordInsetPublicMethod(ledgerMerchantRecordDto,ledgerMerchant1.getId());
        }else{
            //添加新的场地记录
            LedgerMerchant ledgerMerchant1 = this.addLedgerMerchant(ledgerMerchantRecordDto);
            //修改旧的场地记录
            ledgerMerchant.setFailureTime(ledgerMerchant1.getEntryIntoForceTime());
            Integer resultUpdate = ledgerMerchantDao.update(ledgerMerchant);
            if (resultUpdate == 0){
                throw new RuntimeException("更新旧场地记录失败");
            }
            //添加分账信息
            this.ledgerMerchantRecordInsetPublicMethod(ledgerMerchantRecordDto,ledgerMerchant1.getId());
        }
        return ServerResponse.createBySuccess();
    }
    //添加场地公共方法
    private LedgerMerchant addLedgerMerchant(LedgerMerchantRecordDto ledgerMerchantRecordDto){
        LedgerMerchant ledgerMerchant1 = new LedgerMerchant();
        ledgerMerchant1.setMerchantStoreId(ledgerMerchantRecordDto.getMerchantStoreId());
        ledgerMerchant1.setUserId(ledgerMerchantRecordDto.getUserInfo().getId());
        ledgerMerchant1.setSplitCommission(ledgerMerchantRecordDto.getSplitCommission());
        ledgerMerchant1.setDesignatedGoods(ledgerMerchantRecordDto.getDesignatedGoods());
        ledgerMerchant1.setDesignatedGoodsType(ledgerMerchantRecordDto.getDesignatedGoodsType());
        ledgerMerchant1.setRemovalCost(ledgerMerchantRecordDto.getRemovalCost());
        ledgerMerchant1.setFailureStatus(LedgerMerchantFailureStatusEnum.NOT_EXPIRED.getCode());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date time = null;
        try {
            time = format.parse(DateTimeUtils.getSomeDayLaterStartTime(1));
        } catch (Exception e) {
            e.printStackTrace();
        }
        ledgerMerchant1.setEntryIntoForceTime(time);
        Integer result = ledgerMerchantDao.inset(ledgerMerchant1);
        //1.部分商品才添加分账商品记录
        if(ledgerMerchantRecordDto.getDesignatedGoodsType().compareTo(1) == 0 && ledgerMerchantRecordDto.getCheckboxCommodityIdArray().length > 0 ){
            ledgerCommodityDao.insert(ledgerMerchantRecordDto.getCheckboxCommodityIdArray(),ledgerMerchant1.getId());
        }
        if (result == 0) {
            throw new RuntimeException("添加场地记录失败");
        }
        return ledgerMerchant1;
    }

    //添加分账率公共方法
    private void ledgerMerchantRecordInsetPublicMethod(LedgerMerchantRecordDto ledgerMerchantRecordDto, Integer id) {
        ledgerMerchantRecordDto.setLedgerMerchantId(id);
        for (LedgerMerchantRecord l:ledgerMerchantRecordDto.getLedgerMerchantRecordList()) {
            ledgerMerchantRecordDto.setMerchantId(l.getMerchantId());
            ledgerMerchantRecordDto.setShareRate(l.getShareRate());
            ledgerMerchantRecordDto.setType(l.getType());
            Integer resultLed = ledgerMerchantRecordDao.inset(ledgerMerchantRecordDto);
            if (resultLed == 0){
                throw new RuntimeException("添加分账比例失败");
            }
        }
    }

    @Transactional
    @Override
    public ServerResponse editLedgerMerchantOrRecordBatch(LedgerMerchantRecordDto ledgerMerchantRecordDto) {
        //不等于1，2，3，无权限操作
        Integer[] roleIdArray = {
                RoleEnum.AGENT.getRoleId(),
                RoleEnum.SUPER_ADMINISTRATOR.getRoleId(),
                RoleEnum.MERCHANT.getRoleId()
        };
        boolean contains = Arrays.asList(roleIdArray).contains(ledgerMerchantRecordDto.getUserInfo().getRoleId());
        if(!contains){
            return ServerResponse.createByErrorMessage("暂无操作权限！");
        }

        if(ledgerMerchantRecordDto.getMerchantStoreIdArray().length > 0){
           for (int i = 0; i<ledgerMerchantRecordDto.getMerchantStoreIdArray().length; i++){
               ledgerMerchantRecordDto.setMerchantStoreId(ledgerMerchantRecordDto.getMerchantStoreIdArray()[i]);
               LedgerMerchant ledgerMerchant =ledgerMerchantDao.findOneLedgerMerchant(ledgerMerchantRecordDto);
               if(ObjectUtils.isEmpty(ledgerMerchant)){
                   //添加场地记录
                   LedgerMerchant ledgerMerchant1 = this.addLedgerMerchant(ledgerMerchantRecordDto);
                   //添加分账信息
                   this.ledgerMerchantRecordInsetPublicMethod(ledgerMerchantRecordDto,ledgerMerchant1.getId());
               }else {
                   //添加新的场地记录
                   LedgerMerchant ledgerMerchant1 = this.addLedgerMerchant(ledgerMerchantRecordDto);
                   //修改旧的场地记录
                   ledgerMerchant.setFailureTime(ledgerMerchant1.getEntryIntoForceTime());
                   Integer resultUpdate = ledgerMerchantDao.update(ledgerMerchant);
                   if (resultUpdate == 0){
                       throw new RuntimeException("更新旧场地记录失败");
                   }
                   //添加分账信息
                   this.ledgerMerchantRecordInsetPublicMethod(ledgerMerchantRecordDto,ledgerMerchant1.getId());
               }
            }
        }
        return ServerResponse.createBySuccess();
    }

}
